

<!DOCTYPE html>
<html lang="en" color-mode=light>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Vue侦听器(watch)的实践分享 - Hexo</title>
  <meta name="apple-mobile-web-app-capable" content="yes" />
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <meta name="google" content="notranslate" />
  
  <meta name="description" content="前言在开发中遇到一个需求：

现有A、B两页面，其中B...">
  <meta name="author" content="John Doe">
  <link rel="icon" href="/images/icons/favicon-16x16.png" type="image/png" sizes="16x16">
  <link rel="icon" href="/images/icons/favicon-32x32.png" type="image/png" sizes="32x32">
  <link rel="apple-touch-icon" href="/images/icons/apple-touch-icon.png" sizes="180x180">
  <meta rel="mask-icon" href="/images/icons/stun-logo.svg" color="#333333">
  
    <meta rel="msapplication-TileImage" content="/images/icons/favicon-144x144.png">
    <meta rel="msapplication-TileColor" content="#000000">
  

  
<link rel="stylesheet" href="/css/style.css">


  
    
<link rel="stylesheet" href="https://at.alicdn.com/t/font_1445822_p6ry5n7lrr.css">

  

  
    
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css">

  

  
    
      
        
        
<link rel="stylesheet" href="https://cdn.bootcss.com/highlight.js/9.18.1/styles/xcode.min.css" name="highlight-style" mode="light">

      
        
        
<link rel="stylesheet" href="https://cdn.bootcss.com/highlight.js/9.18.1/styles/solarized-dark.min.css" name="highlight-style" mode="dark">

      
  

  <script>
    var CONFIG = window.CONFIG || {};
    var ZHAOO = window.ZHAOO || {};
    CONFIG = {
      isHome: false,
      fancybox: true,
      pjax: false,
      loading: {
        gif: '/images/theme/loading.gif',
        lottie: ''
      },
      lazyload: {
        enable: true,
        only_post: 'false',
        loading: {
          gif: '/images/theme/loading.gif',
          lottie: ''
        }
      },
      donate: {
        enable: false,
        alipay: 'https://pic.izhaoo.com/alipay.jpg',
        wechat: 'https://pic.izhaoo.com/wechat.jpg'
      },
      galleries: {
        enable: true
      },
      fab: {
        enable: true,
        always_show: false
      },
      carrier: {
        enable: false
      },
      daovoice: {
        enable: false
      },
      preview: {
        background: {
          default: '',
          api: ''
        },
        motto: {
          default: '我在开了灯的床头下，想问问自己的心啊。',
          typing: true,
          api: 'https://v2.jinrishici.com/one.json',
          data_contents: '["data","content"]'
        },
      },
      qrcode: {
        enable: false,
        type: 'url',
        image: 'https://pic.izhaoo.com/weapp-code.jpg',
      },
      toc: {
        enable: true
      },
      scrollbar: {
        type: 'default'
      },
      notification: {
        enable: false,
        delay: 4500,
        list: '',
        page_white_list: '',
        page_black_list: ''
      },
      search: {
        enable: false,
        path: ''
      }
    }
  </script>

  

  

<meta name="generator" content="Hexo 6.3.0"></head>

<body class="lock-screen">
  <div class="loading" id="loading"></div>
  
    


  <nav class="navbar">
    <div class="left">
      
        <i class="iconfont iconhome j-navbar-back-home"></i>
      
      
      
        <i class="iconfont iconmoono" id="color-toggle" color-toggle="light"></i>
      
      
    </div>
    <div class="center">Vue侦听器(watch)的实践分享</div>
    <div class="right">
      <i class="iconfont iconmenu j-navbar-menu"></i>
    </div>
    
  </nav>

  
  

<nav class="menu">
  <div class="menu-container">
    <div class="menu-close">
      <i class="iconfont iconbaseline-close-px"></i>
    </div>
    <ul class="menu-content"><li class="menu-item">
        <a href="/ " class="underline "> 首页</a>
      </li><li class="menu-item">
        <a href="/archives/ " class="underline "> 日志</a>
      </li><li class="menu-item">
        <a href="/about " class="underline "> 关于</a>
      </li></ul>
    
      <div class="menu-copyright"><div><p>Powered by <a target="_blank" href="https://hexo.io">Hexo</a>  |  Theme - <a target="_blank" href="https://github.com/izhaoo/hexo-theme-zhaoo">zhaoo</a></p> <p><img class="aaa" src="/images/theme/iconBA.png" style="width:16px; height:18px"/> <a href="https://beian.mps.gov.cn/#/query/webSearch?code=44200102445419" rel="noreferrer" target="_blank">粤公网安备44200102445419</a>       &nbsp; <a href="https://beian.miit.gov.cn/" target="_blank">蜀ICP备2023036693号</a></p><p>&copy;田林</p> </div></div>
    
  </div>
</nav>
  <main id="main">
  <div class="article-wrap">
    <div class="row container">
      <div class="col-xl-3"></div>
      <div class="col-xl-6"><article class="article">
  <div class="wrap">
    <section class="head">
  <img   class="lazyload" data-original="/images/theme/post-image.jpg" src=""  draggable="false">
  <div class="head-mask">
    <h1 class="head-title">Vue侦听器(watch)的实践分享</h1>
    <div class="head-info">
      <span class="post-info-item"><i class="iconfont iconcalendar"></i>December 28, 2023</span>
      
      <span class="post-info-item"><i class="iconfont iconfont-size"></i>4480</span>
    </div>
  </div>
</section>
    <section class="main">
      <section class="content">
        
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><pre><code>在开发中遇到一个需求：
</code></pre>
<p>现有A、B两页面，其中B页面是A页面的新页面（不是父子组件关系），要求：A页面传递id参数，B页面接收传递参数，当A页面不传递参数（undefined）或传空时，B页面保持原先A页面传递过来的id值（B页面接收的参数不可能为空）<br>即：</p>
<ol>
<li>A(id&#x3D;1) &#x3D;&gt; B(id&#x3D;1)</li>
<li>A(不传&amp;id&#x3D;undefined) &#x3D;&gt; B(id&#x3D;1)</li>
<li>A(id&#x3D;2) &#x3D;&gt; B(id&#x3D;2)</li>
<li>…</li>
</ol>
<h2 id="Vue侦听器-watch"><a href="#Vue侦听器-watch" class="headerlink" title="Vue侦听器(watch)"></a>Vue侦听器(watch)</h2><p>在前言中提到的需求，实现的方法有多种，例如<br>（以下将侦听器更换名为监听器）</p>
<ul>
<li>sessionStorage （会话存储） 和 localStorage（本地存储）</li>
<li>Vue状态管理器</li>
<li>Vue监听器(watch)</li>
<li>….</li>
</ul>
<p>本文主要以 <strong>Vue监听器(watch)</strong> 为方法进行实现(主要还是回顾Vue内置的监听方法使用)<br><a target="_blank" rel="noopener" href="https://cn.vuejs.org/guide/essentials/watchers.html">vue官网-侦听器</a></p>
<p>在watch函数中支持监听以下三种数据源类型</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> x = <span class="hljs-title function_">ref</span>(<span class="hljs-number">0</span>)<br><span class="hljs-keyword">const</span> y = <span class="hljs-title function_">ref</span>(<span class="hljs-number">0</span>)<br><br><span class="hljs-comment">// 单个 ref</span><br><span class="hljs-title function_">watch</span>(x, <span class="hljs-function">(<span class="hljs-params">newX</span>) =&gt;</span> &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`x is <span class="hljs-subst">$&#123;newX&#125;</span>`</span>)<br>&#125;)<br><br><span class="hljs-comment">// getter 函数</span><br><span class="hljs-title function_">watch</span>(<span class="hljs-function">() =&gt;</span> x.<span class="hljs-property">value</span> + y.<span class="hljs-property">value</span>,<span class="hljs-function">(<span class="hljs-params">sum</span>) =&gt;</span> &#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`sum of x + y is: <span class="hljs-subst">$&#123;sum&#125;</span>`</span>)<br>  &#125;<br>)<br><br><span class="hljs-comment">// 多个来源组成的数组</span><br><span class="hljs-title function_">watch</span>([x, <span class="hljs-function">() =&gt;</span> y.<span class="hljs-property">value</span>], <span class="hljs-function">(<span class="hljs-params">[newX, newY]</span>) =&gt;</span> &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`x is <span class="hljs-subst">$&#123;newX&#125;</span> and y is <span class="hljs-subst">$&#123;newY&#125;</span>`</span>)<br>&#125;)<br><span class="hljs-comment">//注意，watch监听器无法直接监听响应式对象的属性值，需要使用getter函数方式去进行监听</span><br></code></pre></td></tr></table></figure>
<h2 id="实现"><a href="#实现" class="headerlink" title="实现"></a>实现</h2><p>以上就是监听器大致使用，进入正题，实现前言的需求</p>
<ol>
<li>A页面通过点击事件携带<strong>id参数</strong>跳转至B页面</li>
</ol>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-comment">//A页面</span><br><span class="hljs-keyword">const</span> <span class="hljs-title function_">bindHandleA</span>= (<span class="hljs-params">id</span>)=&gt;&#123;<br>	router.<span class="hljs-title function_">push</span>(&#123;<br>    	<span class="hljs-attr">name</span>: <span class="hljs-string">&quot;B页面&quot;</span>,<br>        <span class="hljs-attr">query</span>: &#123;id&#125;<br>    &#125;);<br>&#125;<br></code></pre></td></tr></table></figure>

<ol start="2">
<li>B页面接收A页面传递过来的参数</li>
</ol>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-comment">//B页面</span><br><span class="hljs-keyword">const</span> parA = <span class="hljs-title function_">ref</span>(); <span class="hljs-comment">//接收参数</span><br>parA.<span class="hljs-property">value</span> = route.<span class="hljs-property">query</span>.<span class="hljs-property">id</span><br></code></pre></td></tr></table></figure>

<ol start="4">
<li>通过onActivated或onMounted生命周期方法进行监听每次传递id的值</li>
</ol>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">let</span> webId = <span class="hljs-literal">null</span>;<br><span class="hljs-keyword">const</span> newActive = <span class="hljs-title function_">ref</span>(<span class="hljs-literal">false</span>);<br><span class="hljs-title function_">onMounted</span>(<span class="hljs-function">() =&gt;</span> &#123;<br>	webId = route.<span class="hljs-property">query</span>.<span class="hljs-property">id</span>;<br>    <span class="hljs-title function_">watch</span>(<span class="hljs-function">()=&gt;</span>route.<span class="hljs-property">query</span>.<span class="hljs-property">id</span>,<span class="hljs-function">(<span class="hljs-params">newID,oldID</span>) =&gt;</span> &#123;<br>    	<span class="hljs-keyword">if</span>(newID === <span class="hljs-literal">undefined</span> || newID === <span class="hljs-string">&#x27;&#x27;</span>)&#123;<br>        	webId = oldID;<br>            newActive.<span class="hljs-property">value</span> = <span class="hljs-literal">false</span>;<br>       	&#125;<br>        <span class="hljs-keyword">if</span>(oldID === <span class="hljs-literal">undefined</span>)&#123;<br>             webId = newID;<br>             newActive.<span class="hljs-property">value</span> = <span class="hljs-literal">true</span>;<br>        &#125;<br>        <span class="hljs-keyword">if</span>(newActive.<span class="hljs-property">value</span>)&#123;<br>        <span class="hljs-comment">//接收传递过来的id值	</span><br>             <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(webId);<br>        &#125;<br>     &#125;);<br>&#125;);<br><span class="hljs-comment">/* 或者可以用onActivated */</span><br><span class="hljs-title function_">onActivated</span>(<span class="hljs-function">() =&gt;</span> &#123;   <br>    <span class="hljs-title function_">watch</span>(<span class="hljs-function">()=&gt;</span>route.<span class="hljs-property">query</span>.<span class="hljs-property">id</span>,<span class="hljs-function">(<span class="hljs-params">newID,oldID</span>) =&gt;</span> &#123;<br>        <span class="hljs-keyword">if</span>(newID === <span class="hljs-literal">undefined</span> || newID === <span class="hljs-string">&#x27;&#x27;</span>)&#123;<br>            webId = oldID;<br>            newActive.<span class="hljs-property">value</span> = <span class="hljs-literal">false</span>;<br>            <span class="hljs-keyword">return</span>;<br>        &#125;<br>        <span class="hljs-keyword">if</span>(oldID === <span class="hljs-literal">undefined</span>)&#123;<br>            webId = newID;<br>            newActive.<span class="hljs-property">value</span> = <span class="hljs-literal">true</span>;<br>            <span class="hljs-keyword">return</span>;<br>        &#125;<br>    &#125;);<br>    <span class="hljs-keyword">if</span>(newActive.<span class="hljs-property">value</span>)&#123;<br>    <span class="hljs-comment">//接收传递过来的id值</span><br>        <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(webId);<br>    &#125;<br>&#125;)<br></code></pre></td></tr></table></figure>

<ol start="5">
<li>完成，无论A页面传递什么id值过来都能保持最新状态同时当A页面传值为空时，在监听中保存了有上一次记录值，依旧能够有记录值在此保存着</li>
</ol>
<h2 id="补充"><a href="#补充" class="headerlink" title="补充"></a>补充</h2><h3 id="深层监听"><a href="#深层监听" class="headerlink" title="深层监听"></a>深层监听</h3><p>监听器的深层监听，以上面的代码为例</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-title function_">watch</span>(<span class="hljs-function">()=&gt;</span>route.<span class="hljs-property">query</span>.<span class="hljs-property">id</span>,<span class="hljs-function">(<span class="hljs-params">newID,oldID</span>) =&gt;</span> &#123;<br>	<span class="hljs-keyword">if</span>(newID === <span class="hljs-literal">undefined</span> || newID === <span class="hljs-string">&#x27;&#x27;</span>)&#123;<br>    	webId = oldID;<br>        newActive.<span class="hljs-property">value</span> = <span class="hljs-literal">false</span>;<br>        <span class="hljs-keyword">return</span>;<br>    &#125;<br>    <span class="hljs-keyword">if</span>(oldID === <span class="hljs-literal">undefined</span>)&#123;<br>        webId = newID;<br>        newActive.<span class="hljs-property">value</span> = <span class="hljs-literal">true</span>;<br>        <span class="hljs-keyword">return</span>;<br>    &#125;<br>  &#125;);<br>    <span class="hljs-keyword">if</span>(newActive.<span class="hljs-property">value</span>)&#123;<br>    <span class="hljs-comment">//接收传递过来的id值</span><br>        <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(webId);<br>    &#125;<br>&#125;,&#123;<span class="hljs-attr">deep</span>: <span class="hljs-literal">true</span>&#125;)<br></code></pre></td></tr></table></figure>
<p>通过<strong>deep:true</strong>开启强制深层监听</p>
<h3 id="注意"><a href="#注意" class="headerlink" title="注意"></a>注意</h3><p><strong>开启了深层监听是无法实现前言提到的需求因为传递回的newID,oldID是相等一样的</strong></p>
<p>在Vue官网介绍中，直接给 watch() 传入一个响应式对象，会隐式地创建一个深层侦听器——该回调函数在所有嵌套的变更时都会被触发：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><br><span class="hljs-keyword">const</span> obj = <span class="hljs-title function_">reactive</span>(&#123; <span class="hljs-attr">count</span>: <span class="hljs-number">0</span> &#125;)<br><br><span class="hljs-title function_">watch</span>(obj, <span class="hljs-function">(<span class="hljs-params">newValue, oldValue</span>) =&gt;</span> &#123;<br>  <span class="hljs-comment">// 在嵌套的属性变更时触发</span><br>  <span class="hljs-comment">// 注意：`newValue` 此处和 `oldValue` 是相等的</span><br>  <span class="hljs-comment">// 因为它们是同一个对象！</span><br>&#125;)<br><br>obj.<span class="hljs-property">count</span>++<br></code></pre></td></tr></table></figure>
<p>相比之下，一个返回响应式对象的 getter 函数，只有在返回不同的对象时，才会触发回调：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-title function_">watch</span>(<br>  <span class="hljs-function">() =&gt;</span> state.<span class="hljs-property">someObject</span>,<br>  <span class="hljs-function">() =&gt;</span> &#123;<br>    <span class="hljs-comment">// 仅当 state.someObject 被替换时触发</span><br>  &#125;<br>)<br></code></pre></td></tr></table></figure>

<blockquote>
<p>谨慎使用<br>深度侦听需要遍历被侦听对象中的所有嵌套的属性，当用于大型数据结构时，开销很大。因此请只在必要时才使用它，并且要留意性能。</p>
</blockquote>
<h3 id="即时回调的侦听器"><a href="#即时回调的侦听器" class="headerlink" title="即时回调的侦听器"></a>即时回调的侦听器</h3><p>watch函数是懒执行状态，只有监听数据源变化时才能执行watch函数回调<br>通过传入 immediate: true 选项来强制侦听器的回调立即执行：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-title function_">watch</span>(<br>  source,<br>  <span class="hljs-function">(<span class="hljs-params">newValue, oldValue</span>) =&gt;</span> &#123;<br>    <span class="hljs-comment">// 立即执行，且当 `source` 改变时再次执行</span><br>  &#125;,<br>  &#123; <span class="hljs-attr">immediate</span>: <span class="hljs-literal">true</span> &#125;<br>)<br></code></pre></td></tr></table></figure>
<h3 id="watchEffect"><a href="#watchEffect" class="headerlink" title="watchEffect()"></a>watchEffect()</h3><p>在vue官网中的介绍是：侦听器的回调使用与源完全相同的响应式状态是很常见的。例如下面的代码，在每当 todoId 的引用发生变化时使用侦听器来加载一个远程资源：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> todoId = <span class="hljs-title function_">ref</span>(<span class="hljs-number">1</span>)<br><span class="hljs-keyword">const</span> data = <span class="hljs-title function_">ref</span>(<span class="hljs-literal">null</span>)<br><br><span class="hljs-title function_">watch</span>(<br>  todoId,<br>  <span class="hljs-keyword">async</span> () =&gt; &#123;<br>    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> <span class="hljs-title function_">fetch</span>(<br>      <span class="hljs-string">`https://jsonplaceholder.typicode.com/todos/<span class="hljs-subst">$&#123;todoId.value&#125;</span>`</span><br>    )<br>    data.<span class="hljs-property">value</span> = <span class="hljs-keyword">await</span> response.<span class="hljs-title function_">json</span>()<br>  &#125;,<br>  &#123; <span class="hljs-attr">immediate</span>: <span class="hljs-literal">true</span> &#125;<br>)<br></code></pre></td></tr></table></figure>
<p>通过watchEffect来简化上述监听函数不需要immediate: true</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-title function_">watchEffect</span>(<span class="hljs-keyword">async</span> () =&gt; &#123;<br>  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> <span class="hljs-title function_">fetch</span>(<br>    <span class="hljs-string">`https://jsonplaceholder.typicode.com/todos/<span class="hljs-subst">$&#123;todoId.value&#125;</span>`</span><br>  )<br>  data.<span class="hljs-property">value</span> = <span class="hljs-keyword">await</span> response.<span class="hljs-title function_">json</span>()<br>&#125;)<br></code></pre></td></tr></table></figure>
<p>这个例子中，回调会立即执行，不需要指定 immediate: true。在执行期间，它会自动追踪 todoId.value 作为依赖（和计算属性类似）。每当 todoId.value 变化时，回调会再次执行。有了 watchEffect()，我们不再需要明确传递 todoId 作为源值。</p>
<h2 id="结尾"><a href="#结尾" class="headerlink" title="结尾"></a>结尾</h2><p>以上就是Vue侦听器(watch)的实践分享的全部内容，在补充中有很多都是Vue官网中的案例和介绍，就不再叙述补充了，详细可以去查看Vue官网中的介绍案例，如不理解的地方欢迎讨论。</p>
<blockquote>
<p><a target="_blank" rel="noopener" href="https://cn.vuejs.org/guide/essentials/watchers.html">Vue官网侦听器</a></p>
</blockquote>

      </section>
      <section class="extra">
        
        
        
        
  <nav class="nav">
    <a></a>
    <a href="/2023/12/28/%E4%BD%BF%E7%94%A8nginx%E9%83%A8%E7%BD%B2hexo%E5%8D%9A%E5%AE%A2%E6%A1%86%E6%9E%B6%E6%90%AD%E5%BB%BA%E5%AE%9E%E8%B7%B5%E5%88%86%E4%BA%AB/">使用nginx部署hexo博客框架搭建实践分享<i class="iconfont iconright"></i></a>
  </nav>

      </section>
      
    </section>
  </div>
</article></div>
      <div class="col-xl-3">
        
          
  <aside class="toc-wrap">
    <h3 class="toc-title">文章目录：</h3>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%89%8D%E8%A8%80"><span class="toc-text">前言</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Vue%E4%BE%A6%E5%90%AC%E5%99%A8-watch"><span class="toc-text">Vue侦听器(watch)</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AE%9E%E7%8E%B0"><span class="toc-text">实现</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%A1%A5%E5%85%85"><span class="toc-text">补充</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B7%B1%E5%B1%82%E7%9B%91%E5%90%AC"><span class="toc-text">深层监听</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B3%A8%E6%84%8F"><span class="toc-text">注意</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8D%B3%E6%97%B6%E5%9B%9E%E8%B0%83%E7%9A%84%E4%BE%A6%E5%90%AC%E5%99%A8"><span class="toc-text">即时回调的侦听器</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#watchEffect"><span class="toc-text">watchEffect()</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BB%93%E5%B0%BE"><span class="toc-text">结尾</span></a></li></ol>
  </aside>

        
      </div>
    </div>
  </div>
</main>
  

<footer class="footer">
  <div class="footer-social"><a 
        href="tencent://message/?Menu=yes&uin=894519210 "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color= '#12B7F5'" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  iconQQ "></i>
      </a><a 
        href="javascript:; "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color= '#09BB07'" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  iconwechat-fill "></i>
      </a><a 
        href="https://www.instagram.com/izhaoo/ "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color= '#DA2E76'" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  iconinstagram "></i>
      </a><a 
        href="https://github.com/zhaoo "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color= '#9f7be1'" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  icongithub-fill "></i>
      </a><a 
        href="mailto:izhaoo@163.com "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color=#FF3B00" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  iconmail"></i>
      </a></div>
  
    <div class="footer-copyright"><div><p>Powered by <a target="_blank" href="https://hexo.io">Hexo</a>  |  Theme - <a target="_blank" href="https://github.com/izhaoo/hexo-theme-zhaoo">zhaoo</a></p> <p><img class="aaa" src="/images/theme/iconBA.png" style="width:16px; height:18px"/> <a href="https://beian.mps.gov.cn/#/query/webSearch?code=44200102445419" rel="noreferrer" target="_blank">粤公网安备44200102445419</a>       &nbsp; <a href="https://beian.miit.gov.cn/" target="_blank">蜀ICP备2023036693号</a></p><p>&copy;田林</p> </div></div>
  
</footer>
  
      <div class="fab fab-plus">
    <i class="iconfont iconplus"></i>
  </div>
  
  
  
  <div class="fab fab-up">
    <i class="iconfont iconcaret-up"></i>
  </div>
  
  
  
    
<script src="/js/color-mode.js"></script>

  
  
</body>

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>





  
<script src="https://cdn.bootcdn.net/ajax/libs/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>




  
<script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js"></script>








<script src="/js/utils.js"></script>
<script src="/js/script.js"></script>







  <script>
    (function () {
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
      } else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
      }
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>












</html>